package logic

import (
	"context"
	"fmt"
	"houses/model/cache"
	"houses/pkg"
	"math/rand"
	"strconv"
	"time"

	"houses/housesrpc/housesrpc"
	"houses/housesrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SmsCaptchaLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSmsCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SmsCaptchaLogic {
	return &SmsCaptchaLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SmsCaptchaLogic) SmsCaptcha(in *housesrpc.SmsCaptchaquest) (*housesrpc.SmsCaptchaResponse, error) {
	// todo: add your logic here and delete this line
	count, _ := cache.Rdb.Get(l.ctx, "SmsKey"+in.Number).Int64()
	if count >= 1 {
		return nil, fmt.Errorf("当前已经发过一次了,请1小时后再试")
	}
	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Number, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}

	if sms.Code != 2 {
		return nil, fmt.Errorf(sms.Msg)
	}

	cache.Rdb.Set(l.ctx, "SmsKey"+in.Number, code, time.Minute*5)
	cache.Rdb.Incr(l.ctx, "SmsKey"+in.Number)
	cache.Rdb.Expire(l.ctx, "SmsKey"+in.Number, time.Hour*1)
	return &housesrpc.SmsCaptchaResponse{
		Code:  int64(sms.Code),
		Msg:   sms.Msg,
		Smsid: sms.Smsid,
	}, nil
}
